﻿using FNN.EventArguments;
using Sparrow.Chart;
using System.Linq;
using System.Windows;

namespace GraphicFNN
{
    /// <summary>
    /// Логика взаимодействия для ChartWindow.xaml
    /// </summary>
    public partial class ChartWindow : Window
    {   
        public void CatchIterationChanged(object sender, IterationChangedEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                LblIterationNumber.Content = e.IterationNumber;
            });
        }
             
        public void CatchResultsImproved(object sender, IterationChangedEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                var existElement = MainSeries.Points.FirstOrDefault(o => ((DoublePoint)o).Data == e.IterationNumber) as DoublePoint;
                if ((existElement != null) && (existElement.Value < e.IterationResult))
                {
                    existElement.Value = e.IterationResult;
                    RefreshSeries();
                }
                else if (existElement == null)
                {
                    if (MainSeries.Points.Count == 50)
                    {
                        MainSeries.Points.Remove(MainSeries.Points.First());
                    }
                    MainSeries.Points.Add(new DoublePoint() { Data = e.IterationNumber, Value = e.IterationResult });
                    RefreshSeries();
                }

                var minYValue = MainSeries.Points.Min(o => ((DoublePoint)o).Value);
                var maxYValue = MainSeries.Points.Max(o => ((DoublePoint)o).Value);
                var maxXValue = MainSeries.Points.Max(o => ((DoublePoint)o).Data);
                
                XAxis.MaxValue = maxXValue + 10;
                YAxis.MinValue = minYValue - 10;
                YAxis.MaxValue = maxYValue + 10;

                YAxis.Refresh();
                XAxis.Refresh();                
            });
        }
        
        private void RefreshSeries()
        {
            MainSeries.Refresh();
        }

        public ChartWindow()
        {
            InitializeComponent();
        }
    }
}